﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ERPStudio;
using System.Data.SqlClient;
using Fares.DataSets;

namespace Fares
{
    public partial class UrmarireComenziFrm : FrmWorkspace
    {
        public UrmarireComenziFrm(ModuleClass mc):base(mc)
        {
            InitializeComponent();
            workConnString = mc.workConnectionString;
            eSRPDataSetUrmarireComenzi.ProductieRealizata.DataColumn.DefaultValue = DateTime.Now;
        }

        private void UrmarireComenziFrm_Load(object sender, EventArgs e)
        {
            SqlConnection con = DeschideConexiune(workConnString);
            Setup(con);
            this.productieRealizataTableAdapter.Connection = con;
            this.productieRealizataTableAdapter.Fill(this.eSRPDataSetUrmarireComenzi.ProductieRealizata);
            this.unitatiMasuraTableAdapter.Connection = con;
            this.unitatiMasuraTableAdapter.Fill(this.eSRPDataSetUrmarireComenzi.UnitatiMasura);
            this.articoleTableAdapter.Connection = con;
            this.articoleTableAdapter.Fill(this.eSRPDataSetUrmarireComenzi.Articole);
            this.documenteDetaliuTableAdapter.Connection = con;
            this.documenteDetaliuTableAdapter.Fill(this.eSRPDataSetUrmarireComenzi.DocumenteDetaliu);
            this.fares_ParteneriCUITableAdapter.Connection = con;
            this.fares_ParteneriCUITableAdapter.Fill(this.eSRPDataSetUrmarireComenzi.fares_ParteneriCUI);
            this.documenteTableAdapter.Connection = con;
            this.documenteTableAdapter.Fill(this.eSRPDataSetUrmarireComenzi.Documente,ModuleInfo.CodUnitate);
            InchideConexiune(con);

            AddBindingSource(productieRealizataBindingSource);
            AddTableAdaptor(productieRealizataTableAdapter.Adapter);
            AddButton("Fisa Productie", global::ERPStudio.Properties.Resources._001_44, FisaProductie, ToolStripItemAlignment.Right, false);
            DeLaDTP_ValueChanged(sender, null);
        }

        private void Setup(SqlConnection wConn)
        {

            #region Setare data in format romanesc
            ///data in format romanesc
            ///
            DeLaDTP.Format = DateTimePickerFormat.Custom;
            DeLaDTP.CustomFormat = "dd.MM.yyyy";
            PanaLaDTP.Format = DateTimePickerFormat.Custom;
            PanaLaDTP.CustomFormat = "dd.MM.yyyy";
            
            #endregion

            //#region Determinarea seriilor numerice implicite
            //Object ret = GetSetupValue("FaresSetup", "IDSerie", ModuleInfo.CodUnitate, wConn);
            //String val = String.Empty;
            //if (ret != null && ret != DBNull.Value)
            //    val = ret.ToString();
            //else
            //{
            //    while (ret == null)
            //    {
            //        MessageBox.Show("Modulul Parteneri nu a fost configurat. \nVa rugam sa-l configurati!",
            //                "Eroare",
            //                MessageBoxButtons.OK,
            //                MessageBoxIcon.Hand);
            //        FaresSetupFrm frm = new FaresSetupFrm(this.ModuleInfo);
            //        frm.ShowDialog();
            //        ret = GetSetupValue("FaresSetup", "IDSerie", ModuleInfo.CodUnitate, wConn);
            //    }
            //    val = ret.ToString();
            //}
            //SeriiNumerice.Add("DOC", val);
            //SerieNumerica = val;
            /////determina seria numerica pentru bonurile de consum
            /////
            //ret = GetSetupValue("FaresSetup", "IDSerieBC", ModuleInfo.CodUnitate, wConn);
            //if (ret != null && ret != DBNull.Value)
            //    val = ret.ToString();
            //SeriiNumerice.Add("BC", val);

            //ret = GetSetupValue("FaresSetup", "IDSerieBF", ModuleInfo.CodUnitate, wConn);
            //if (ret != null && ret != DBNull.Value)
            //    val = ret.ToString();
            //SeriiNumerice.Add("BF", val);

            //#endregion

            //#region Determinare luna,an curent
            //Object retObj = GetSetupValue("FaresSetup", "LunaCurenta", ModuleInfo.CodUnitate, wConn);
            //if (retObj != null && retObj != DBNull.Value)
            //    LunaCurenta = Convert.ToInt32(retObj);
            //retObj = GetSetupValue("FaresSetup", "AnCurent", ModuleInfo.CodUnitate, wConn);
            //if (retObj != null && retObj != DBNull.Value)
            //    AnulCurent = Convert.ToInt32(retObj);
            //#endregion

            //#region Setare valori implicite data
            //UltimaZiLunaCurenta = new DateTime(AnulCurent, LunaCurenta, 1).AddMonths(1).AddDays(-1);
            //eSRPDataSet.Documente.DataDocColumn.DefaultValue = UltimaZiLunaCurenta;
            //eSRPDataSet.Documente.DataScadentaColumn.DefaultValue = UltimaZiLunaCurenta.AddDays(30);
            //eSRPDataSet.Documente.DataDocReceptieColumn.DefaultValue = UltimaZiLunaCurenta;
            //eSRPDataSet.Documente.DataContractColumn.DefaultValue = UltimaZiLunaCurenta;
            //#endregion
        }


        private List<BindingSource> listBS = new List<BindingSource>();
        private List<SqlDataAdapter> listTA = new List<SqlDataAdapter>();

        private void FisaProductie(object sender, EventArgs e)
        {
            Salvare(this, null);
            UrmarireSelectieDataFrm frmSel = new UrmarireSelectieDataFrm();
            frmSel.ShowDialog();

            String selectStr = String.Empty;
            ///genereaza inregistrarile cu productia realizata
            ///Creaza sirul cu inregistrarile selectate
            foreach (DataRowView dr2 in SelectBindingSource)
            {
                ESRPDataSetUrmarireComenzi.DocumenteDetaliuRow drr2 = dr2.Row as ESRPDataSetUrmarireComenzi.DocumenteDetaliuRow;
                if(selectStr!=string.Empty)
                    selectStr+=",";
                if (drr2.Selected)
                    selectStr += drr2.IDDocumentDetaliu.ToString();
            }

            String dtSel = frmSel.SelectedDate.Year.ToString() + "-" + frmSel.SelectedDate.Month.ToString() + "-" +frmSel.SelectedDate.Day.ToString();
            SqlConnection con = DeschideConexiune(workConnString);
            SqlCommand cmd = new SqlCommand("fares_AdaugaProductieRealizata", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add(new SqlParameter("@IDDocumenteDetaliuSelectate", selectStr));
            cmd.Parameters.Add(new SqlParameter("@DataProductie", dtSel ));
            cmd.ExecuteScalar();
            this.productieRealizataTableAdapter.Connection = con;
            this.productieRealizataTableAdapter.Fill(this.eSRPDataSetUrmarireComenzi.ProductieRealizata);

            ESRPDataSetUrmarireComenzi eSRPDS = new ESRPDataSetUrmarireComenzi();
            Cursor.Current = Cursors.AppStarting;




            PreviewRaportFrm frm = new PreviewRaportFrm("", null, ModuleInfo);

            frm.NumeRaport = "FisaProductie.rdlc";


            foreach (BindingSource bs in listBS)
                if (bs != null) bs.Dispose();
            listBS.Clear();
            listBS.Add(new BindingSource(eSRPDS, "fares_FisaProductie"));

            listTA.Clear();
            listTA.Add(new SqlDataAdapter("SELECT * FROM [fares_FisaProductie] WHERE Data='" +dtSel.ToString() + "'", cmd.Connection));
            listTA[0].SelectCommand.CommandType = CommandType.Text;
            listTA[0].Fill(eSRPDS.fares_FisaProductie);

            //listTA.Add(new SqlDataAdapter("SELECT * FROM [FaresSetup] WHERE CodUnitate=" + ModuleInfo.CodUnitate.ToString(), cmd.Connection));
            //listTA[1].SelectCommand.CommandType = CommandType.Text;
            //listTA[1].Fill(eSRPDS.FaresSetup);
            //listBS.Add(new BindingSource(eSRPDS, "FaresSetup"));

            //listTA.Add(new SqlDataAdapter("SELECT * FROM [DocumentePlata] WHERE IDDocumentPlata =" + ddr.IDDocumentPlata, cmd.Connection));
            //listTA[2].SelectCommand.CommandType = CommandType.Text;
            //listTA[2].Fill(eSRPDS.DocumentePlata);
            //listBS.Add(new BindingSource(eSRPDS, "DocumentePlata"));

            //listTA.Add(new SqlDataAdapter("SELECT * FROM [fares_viewDetaliuPlata] WHERE IDDocumentPlata =" + ddr.IDDocumentPlata.ToString(), cmd.Connection));
            //listTA[3].SelectCommand.CommandType = CommandType.Text;
            //listTA[3].Fill(eSRPDS.fares_viewDetaliuPlata);
            //listBS.Add(new BindingSource(eSRPDS, "fares_viewDetaliuPlata"));

            //listTA.Add(new SqlDataAdapter("SELECT * FROM [fares_ViewParteneri] WHERE IDPartener =" + ddr.IDPartener.ToString(), cmd.Connection));
            //listTA[4].SelectCommand.CommandType = CommandType.Text;
            //listTA[4].Fill(eSRPDS.fares_ViewParteneri);
            //listBS.Add(new BindingSource(eSRPDS, "fares_ViewParteneri"));

            ////listTA.Add(new SqlDataAdapter("SELECT * FROM [aspnet_Users] WHERE UserID ='" + ddr.UserId.ToString() + "'", DeschideConexiune("AdminConnectionString")));
            ////listTA[5].SelectCommand.CommandType = CommandType.Text;
            ////listTA[5].Fill(eSRPDS.aspnet_Users);
            ////listBS.Add(new BindingSource(eSRPDS, "aspnet_Users"));


            //listTA.Add(new SqlDataAdapter("SELECT * FROM [fares_viewUnitati] WHERE CodUnitate=" + ModuleInfo.CodUnitate.ToString(), cmd.Connection));
            //listTA[5].SelectCommand.CommandType = CommandType.Text;
            //listTA[5].Fill(eSRPDS.fares_viewUnitati);
            //listBS.Add(new BindingSource(eSRPDS, "fares_viewUnitati"));

            //String reprezentandStr = String.Empty;
            //for (int i = 0; i < listBS[3].Count; i++)
            //{
            //    DataSets.ESRPDataSet.fares_viewDetaliuPlataRow rd = ((DataRowView)listBS[3].Current).Row as DataSets.ESRPDataSet.fares_viewDetaliuPlataRow;
            //    if (reprezentandStr != String.Empty)
            //        reprezentandStr += ",";
            //    reprezentandStr += rd.NrDoc.ToString() + "/" + rd.DataDoc.ToShortDateString();
            //}

            ////String[] nume = new String[50], functii = new String[50];
            ////for (int i = 0; i < 50; i++)
            ////{
            ////    nume[i] = String.Empty;
            ////    functii[i] = String.Empty;
            ////}
            ////for (int i = 0; i < Math.Min(listBS[6].Count, 50); i++)
            ////{
            ////    listBS[6].Position = i;
            ////    nume[i] = ((DataRowView)((BindingSource)listBS[6]).Current)["Nume"].ToString();
            ////    functii[i] = ((DataRowView)((BindingSource)listBS[6]).Current)["Functia"].ToString();

            ////}


            InchideConexiune(con);

            frm.AddDataSource("fares_FisaProductie", listBS[0]);
     

            frm.SetWindowFormat(true);



            foreach (SqlDataAdapter da in listTA)
                if (da != null) da.Dispose();
            listTA.Clear();
            frm.MdiParent = this.MdiParent;

            NumberToWordsConverter nc = new NumberToWordsConverter();
            //frm.AddParameter("Adica", nc.NumberToWords(ddr.ValoareTotala), true);
            //frm.AddParameter("Reprezentand", reprezentandStr, true);
            //frm.AddParameter("Functii", functii, true);

            frm.Show();
            cmd.Dispose();



            Cursor.Current = Cursors.Default;
        }

        private void TotSelectieCB_CheckedChanged(object sender, EventArgs e)
        {
            foreach (DataRowView dr in documenteBindingSource)
            {
                ESRPDataSetUrmarireComenzi.DocumenteRow drr = dr.Row as ESRPDataSetUrmarireComenzi.DocumenteRow;
                drr.Selected = TotSelectieCB.Checked;
                drr.EndEdit();
                SelectBindingSource.Filter = "IDDocument=" + drr.IDDocument.ToString();
                foreach (DataRowView dr2 in SelectBindingSource)
                {
                    ESRPDataSetUrmarireComenzi.DocumenteDetaliuRow drr2 = dr2.Row as ESRPDataSetUrmarireComenzi.DocumenteDetaliuRow;
                    drr2.Selected = drr.Selected;
                    drr2.EndEdit();
                }
            }
        }

        private void DeLaDTP_ValueChanged(object sender, EventArgs e)
        {
            documenteBindingSource.Filter = "DataStartProductie>='" + DeLaDTP.Value.Year.ToString() + "-" + DeLaDTP.Value.Month.ToString() + "-" + DeLaDTP.Value.Day.ToString() + "' AND DataStartProductie<='" +
                 PanaLaDTP.Value.Year.ToString() + "-" + PanaLaDTP.Value.Month.ToString() + "-" + PanaLaDTP.Value.Day.ToString() + "'";
        }

        private void documenteDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex != selectColumn.Index)
                return;
            ESRPDataSetUrmarireComenzi.DocumenteRow docRow = ((DataRowView)documenteDGV.Rows[e.RowIndex].DataBoundItem).Row as ESRPDataSetUrmarireComenzi.DocumenteRow;
            SelectBindingSource.Filter = "IDDocument=" + docRow.IDDocument.ToString();
            foreach (DataRowView dr in SelectBindingSource)
            {
                ESRPDataSetUrmarireComenzi.DocumenteDetaliuRow drr = dr.Row as ESRPDataSetUrmarireComenzi.DocumenteDetaliuRow;
                drr.Selected = !docRow.Selected;
                drr.EndEdit();
            }
        }
    }
}
